<template>
  <div class="cancel-container">
    <el-card class="cancel-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><CloseBold /></el-icon>
          <span>撤销申请</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <!-- 撤销原因 -->
        <el-form-item label="撤销原因" prop="comment">
          <el-input
            v-model="formData.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入撤销申请的原因..."
            maxlength="300"
            show-word-limit
            :disabled="loading"
          />
        </el-form-item>

        <!-- 申请信息预览 -->
        <el-form-item>
          <el-alert
            title="申请信息"
            :description="`申请金额：¥${application.amount.toFixed(2)} | 费用类型：${expenseTypeLabel(application.expenseType)} | 当前状态：${statusText(application.status)}`"
            type="info"
            :closable="false"
            show-icon
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="danger" :loading="loading" @click="handleCancel" :icon="CloseBold">
            {{ loading ? '撤销中...' : '确认撤销' }}
          </el-button>
          <el-button @click="$emit('cancel')" :icon="Close"> 取消操作 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // 引入Element Plus消息组件
import { CloseBold, Close } from '@element-plus/icons-vue' // 引入图标
import { useApplicationStore } from '@/store/application'
import type { ReimbursementApplication } from '@/services/models'
import { STATUS_LABELS, EXPENSE_TYPE_LABELS } from '@/services/models'

const props = defineProps<{
  application: ReimbursementApplication
}>()

const emit = defineEmits<{
  cancel: []
  success: [application: ReimbursementApplication]
}>()

const store = useApplicationStore()

// 表单数据
const formData = reactive({
  comment: '',
})

// 表单验证规则
const formRules = {
  comment: [
    { required: true, message: '请填写撤销原因', trigger: 'blur' },
    { min: 5, max: 300, message: '撤销原因长度在 5 到 300 个字符', trigger: 'blur' },
  ],
}

const loading = ref(false)
const formRef = ref() // 表单引用

// 状态文本
const statusText = (status: string) => STATUS_LABELS[status as keyof typeof STATUS_LABELS] || '未知'

// 费用类型标签
const expenseTypeLabel = (type: string) =>
  EXPENSE_TYPE_LABELS[type as keyof typeof EXPENSE_TYPE_LABELS] || '未知类型'

// 撤销申请
const handleCancel = async () => {
  if (!formRef.value) return
  // 表单验证
  const valid = await formRef.value.validate()

  // 如果验证失败，直接返回，不执行后续逻辑
  if (!valid) {
    return
  }
  try {
    // 确认撤销操作
    await ElMessageBox.confirm(
      '确定要撤销这个申请吗？撤销后将无法恢复，需要重新提交申请。',
      '确认撤销',
      {
        confirmButtonText: '确定撤销',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    loading.value = true
    await store.cancelApplication(props.application.id, formData.comment)

    ElMessage({
      type: 'success',
      message: '申请已成功撤销！',
      duration: 3000,
    })

    // 触发成功事件
    emit('success', props.application)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: `撤销失败：${error.message}`,
        duration: 5000,
      })
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.cancel-container {
  max-width: 600px;
  margin: 0 auto;
}

.cancel-card {
  border-radius: 12px;
  border: 2px solid #f56c6c;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  font-size: 18px;
  color: #f56c6c;
}

/* 自定义表单样式 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
  margin-right: 12px;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: none;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

/* 提示框样式 */
:deep(.el-alert) {
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

:deep(.el-alert--info) {
  background-color: #f0f9ff;
  border-color: #b3d8ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cancel-container {
    margin: 10px;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }

  :deep(.el-button) {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
}

@media (max-width: 480px) {
  .card-header {
    font-size: 14px;
  }

  :deep(.el-form-item__label) {
    width: 70px !important;
    font-size: 14px;
  }
}
</style>
